package com.reggie.console.controller;


import com.reggie.acl.dataobject.ShoppingCart;
import com.reggie.common.util.ReggieContext;
import com.reggie.console.annotation.AuthRule;
import com.reggie.console.dto.ResultDTO;
import com.reggie.console.enums.ReggieRole;
import com.reggie.console.util.ResultBuilder;
import com.reggie.service.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * <p>
 * 购物车 前端控制器
 * </p>
 *
 * @author yth
 * @since 2023-02-04
 */
@Slf4j
@RestController
@RequestMapping("/shoppingCart")
@AuthRule(roles = {ReggieRole.CUSTOMER})
public class ShoppingCartController {

    @Autowired
    private ShoppingCartService shoppingCartService;

    /**
     * 查询购物车中的记录<p>
     * 结果根据创建时间降序排序
     *
     * @return 数据
     */
    @GetMapping("/list")
    public ResultDTO<List<ShoppingCart>> list() {
        long userId = ReggieContext.getInstance().getUserId();
        List<ShoppingCart> shoppingCarts = shoppingCartService.listByUserId(userId);
        return ResultBuilder.ok(shoppingCarts);
    }


    /**
     * 添加菜品或套餐到购物车中
     *
     * @param shoppingCart 数据
     * @return 数据
     */
    @PostMapping("/add")
    public ResultDTO<ShoppingCart> save(@RequestBody ShoppingCart shoppingCart) {
        long userId = ReggieContext.getInstance().getUserId();
        shoppingCart.setUserId(userId);
        ShoppingCart cart = shoppingCartService.saveShoppingCart(shoppingCart);
        return ResultBuilder.ok(cart);
    }

    /**
     * 清空购物车
     *
     * @return 消息
     */
    @DeleteMapping("/clean")
    public ResultDTO<String> clean() {
        long userId = ReggieContext.getInstance().getUserId();
        shoppingCartService.clean(userId);
        return ResultBuilder.ok("清空购物车成功");
    }

    /**
     * 减少一个购物车中某食品
     *
     * @param shoppingCart id/菜品id/套餐id
     * @return 数据
     */
    @PostMapping("/sub")
    public ResultDTO<ShoppingCart> sub(@RequestBody ShoppingCart shoppingCart) {
        long userId = ReggieContext.getInstance().getUserId();
        shoppingCart.setUserId(userId);
        ShoppingCart sc = shoppingCartService.sub(shoppingCart, 1);
        return ResultBuilder.ok(sc);
    }

}

